package com.tomorrowbbs.service.impl;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.tomorrowbbs.domain.ForumArticle;
import com.tomorrowbbs.domain.UserInfo;
import com.tomorrowbbs.domain.UserMessage;
import com.tomorrowbbs.domain.constants.Constants;
import com.tomorrowbbs.domain.dto.FileUploadDto;
import com.tomorrowbbs.domain.enums.*;
import com.tomorrowbbs.domain.vo.PaginationResultVo;
import com.tomorrowbbs.exception.BusinessException;
import com.tomorrowbbs.mapper.ForumArticleMapper;
import com.tomorrowbbs.mapper.UserInfoMapper;
import com.tomorrowbbs.utils.FileUtils;
import com.tomorrowbbs.utils.StringTools;
import com.tomorrowbbs.utils.SysCacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tomorrowbbs.mapper.ForumCommentMapper;
import com.tomorrowbbs.domain.ForumComment;
import com.tomorrowbbs.service.IForumCommentService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 评论Service业务层处理
 * 
 * @author zjz
 * @date 2024-11-09
 */
@Service
public class ForumCommentServiceImpl implements IForumCommentService 
{
    @Autowired
    private ForumCommentMapper forumCommentMapper;
    @Autowired
    private ForumArticleMapper forumArticleMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserInfoServiceImpl userInfoServiceImpl;
    @Autowired
    private UserMessageServiceImpl userMessageServiceImpl;
    @Autowired
    private FileUtils fileUtils;

    /**
     * 查询评论
     * 
     * @param commentId 评论主键
     * @return 评论
     */
    @Override
    public ForumComment selectForumCommentByCommentId(Long commentId)
    {
        return forumCommentMapper.selectForumCommentByCommentId(commentId);
    }

    /**
     * 查询评论列表
     * 
     * @param forumComment 评论
     * @return 评论
     */
    @Override
    public List<ForumComment> selectForumCommentList(ForumComment forumComment)
    {
        List<ForumComment> list = forumCommentMapper.selectForumCommentList(forumComment);

        //获取二级评论
        if(forumComment.getLoadChildren()!=null && forumComment.getLoadChildren()){
            ForumComment subComment = new ForumComment();
            subComment.setQueryLikeType(forumComment.getQueryLikeType());
            subComment.setCurrentUserId(forumComment.getCurrentUserId());
            subComment.setArticleId(forumComment.getArticleId());
            subComment.setStatus(forumComment.getStatus());
            List<Long> pcommentIdList =list.stream().map(ForumComment::getCommentId).distinct().collect(Collectors.toList());
            subComment.setPcommentIdList(pcommentIdList);

            List<ForumComment> subCommentList = forumCommentMapper.selectForumCommentList(subComment);
            Map<Long,List<ForumComment>> tempMap = subCommentList.stream().collect(Collectors.groupingBy(ForumComment::getPCommentId));
            list.forEach(item->{
                item.setChildren(tempMap.get(item.getCommentId()));
            });
        }

        return list;
    }


    /**
     * 新增评论
     * 
     * @param forumComment 评论
     * @return 结果
     */
    @Override
    public int insertForumComment(ForumComment forumComment)
    {
        return forumCommentMapper.insertForumComment(forumComment);
    }

    /**
     * 修改评论
     * 
     * @param forumComment 评论
     * @return 结果
     */
    @Override
    public int updateForumComment(ForumComment forumComment)
    {
        return forumCommentMapper.updateForumComment(forumComment);
    }

    /**
     * 批量删除评论
     * 
     * @param commentIds 需要删除的评论主键
     * @return 结果
     */
    @Override
    public int deleteForumCommentByCommentIds(Long[] commentIds)
    {
        return forumCommentMapper.deleteForumCommentByCommentIds(commentIds);
    }

    /**
     * 删除评论信息
     * 
     * @param commentId 评论主键
     * @return 结果
     */
    @Override
    public int deleteForumCommentByCommentId(Long commentId)
    {
        return forumCommentMapper.deleteForumCommentByCommentId(commentId);
    }

    @Override
    public int countForumComments(ForumComment comment) {
        return forumCommentMapper.countForumComments(comment);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeTopType(String userId, Long commentId, Integer topType) {
        CommentTopTypeEnum topTypeEnum = CommentTopTypeEnum.getByType(topType);
        if(topTypeEnum == null){
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        ForumComment forumComment = forumCommentMapper.selectForumCommentByCommentId(commentId);
        if (forumComment == null){
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        ForumArticle forumArticle = forumArticleMapper.selectForumArticleByArticleId(forumComment.getArticleId());
        if (forumArticle == null){
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }

        if (!forumArticle.getUserId().equals(userId)|| forumComment.getPCommentId() !=0){
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        if(forumComment.getTopType().equals(topType)){
            return;
        }
        if (CommentTopTypeEnum.TOP.getType().equals(topType)){
            forumCommentMapper.updateTopTypeByArticleId(forumComment.getArticleId());
        }

        ForumComment updateInfo = new ForumComment();
        updateInfo.setTopType(topType);
        updateInfo.setCommentId(commentId);
        forumCommentMapper.updateForumComment(updateInfo);

    }

    @Override
    public void postComment(ForumComment comment, MultipartFile image) {
        ForumArticle forumArticle = forumArticleMapper.selectForumArticleByArticleId(comment.getArticleId());
        if (forumArticle == null){
            throw new BusinessException("回复的文章不存在");
        }
        ForumComment pComment = null;
        if (comment.getPCommentId() != 0){
            pComment = forumCommentMapper.selectForumCommentByCommentId(comment.getPCommentId());
            if (pComment == null){
                throw new BusinessException("回复的评论不存在");
            }
        }

        //判断回复的用户是否存在
        if(!StringTools.isEmpty(comment.getReplyUserId())){
            UserInfo userInfo = userInfoMapper.selectUserInfoByUserId(comment.getReplyUserId());
            if (userInfo==null){
                throw new BusinessException("回复的用户不存在");
            }
            comment.setReplyNickName(userInfo.getNickName());
        }
        comment.setPostTime(new Date());

        //上传图片
        if (image != null){
            FileUploadDto fileUploadDto = fileUtils.uploadFile2Local(image,Constants.FILE_FOLDER_IMAGE,FileUploadTypeEnum.COMMENT_IMAGE);
            comment.setImgPath(fileUploadDto.getLocalPath());
        }

        Boolean needAudit = SysCacheUtils.getSysSetting().getAuditSetting().getCommentAudit();

        comment.setStatus(needAudit? CommentStatusEnum.NO_AUDIT.getStatus():CommentStatusEnum.AUDIT.getStatus());
        forumCommentMapper.insertForumComment(comment);
        if (needAudit){
            return;
        }
        updateCommentInfo(comment,forumArticle,pComment);

    }


    //更新用户积分
    public void updateCommentInfo(ForumComment comment, ForumArticle forumArticle, ForumComment pComment){
        Long commentIntegral = SysCacheUtils.getSysSetting().getCommentSetting().getCommentIntegral();
        if (commentIntegral > 0){
            userInfoServiceImpl.updateUserIntegral(comment.getUserId(), UserIntegralOperTypeEnum.POST_COMMENT, UserIntegralChangeTypeEnum.ADD.getChangeType(), commentIntegral);
        }

        //增加文章评论数（只增加一级评论）
//        if(comment.getCommentId() == 0){
//            forumArticleMapper.updateArticleCount(UpdateArticleCountTypeEnum.COMMENT_COUNT.getType(), Constants.ONE,comment.getArticleId());
//        }
        //所有评论都增加
        forumArticleMapper.updateArticleCount(UpdateArticleCountTypeEnum.COMMENT_COUNT.getType(), Constants.ONE, comment.getArticleId());
        //记录消息
        UserMessage userMessage = new UserMessage();
        userMessage.setMessageType(MessageTypeEnum.COMMENT.getType());
        userMessage.setCreateTime(new Date());
        userMessage.setArticleId(comment.getArticleId());
        userMessage.setCommentId(comment.getCommentId());
        userMessage.setSendUserId(comment.getUserId());
        userMessage.setSendNickName(comment.getNickName());
        userMessage.setStatus(MessageStatusEnum.NO_READ.getStatus());
        userMessage.setArticleTitle(forumArticle.getTitle());
        if(comment.getCommentId() == 0){
            userMessage.setReceivedUserId(forumArticle.getUserId());
        }else if (comment.getPCommentId() != 0 && StringTools.isEmpty(comment.getReplyUserId())){
            userMessage.setReceivedUserId(pComment.getUserId());
        }else if (comment.getPCommentId() !=0 && !StringTools.isEmpty(comment.getReplyUserId())){
            userMessage.setReceivedUserId(comment.getReplyUserId());
        }

        if (!comment.getUserId().equals(userMessage.getReceivedUserId())){
            userMessageServiceImpl.insertUserMessage(userMessage);
        }

    }


}












